<template>
  <view class="confirm-page">
    <!-- 收货地址 -->
    <view class="address-box" @tap="changeAddress">
      <text class="default-mark" v-if="defaultAddress.isDefault === 1">默认</text>
      <text class="warn-mark" v-else>非默认</text>
      <text class="area-address">
        {{ defaultAddress.province + defaultAddress.city + defaultAddress.district }}
      </text>
      <p class="detail-address">{{ defaultAddress.detailAddress }}</p>
      <p class="accept-cellphone">{{ defaultAddress.receiverName + " " + defaultAddress.receiverPhone }}</p>
      <text class="gt" decode="true">&gt;</text>
    </view>

    <!-- 商品容器（含列表 + 底部合计 & 按钮） -->
    <view class="confirm-goods-container">
      <view class="confirm-goods-list">
        <view
          v-for="(item, index) in checkedItems"
          :key="item.cartId || item.id"
          class="confirm-goods-item"
        >
          <image
            class="confirm-goods-image"
            :src="item.image"
            mode="aspectFill"
          ></image>
          <view class="confirm-goods-info">
            <text class="goods-name">{{ item.name }}</text>
            <text class="goods-price">￥{{ item.price.toFixed(2) }}</text>
            <text class="goods-num">× {{ item.num }}</text>
          </view>
        </view>
      </view>

      <!-- 合计金额 -->
      <text class="total-text">合计：<text class="total-amount">￥{{ totalPrice.toFixed(2) }}</text></text>

      <!-- 支付按钮 -->
      <button class="pay-btn" @tap="handlePay">生成订单</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted,onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDefaultAddress } from '@/api/Addressapi.js'
import { createOrder } from '@/api/Productapi.js'; // 路径按实际调整
import userManager from '@/common/utils/user.js'

// 默认地址
const defaultAddress = ref({
  addressId: null,
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: 0
})

// 选中的商品
const checkedItems = ref([])

onLoad((options) => {
  if (options.carts) {
    try {
      checkedItems.value = JSON.parse(decodeURIComponent(options.carts))
    } catch (e) {
      console.error('解析购物车数据失败:', e)
      uni.showToast({ title: '数据异常', icon: 'none' })
      setTimeout(() => uni.navigateBack(), 1500)
    }
  } else{
    uni.showToast({ title: '未选择商品', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})

onMounted(async () => {
  // 首次加载
  await loadDefaultAddress()

  // 👇 监听地址变更事件（注意：事件名建议语义清晰）
  uni.$on('addressChanged', loadDefaultAddress)
})

// 页面销毁时移除监听，防止内存泄漏
onUnmounted(() => {
  uni.$off('addressChanged', loadDefaultAddress)
})

const totalPrice = computed(() => {
  return checkedItems.value.reduce((sum, item) => sum + item.price * item.num, 0)
})

const changeAddress = () => {
  uni.navigateTo({ url: '/pages/address/address' })
}

const handlePay = async () => {
	const user = userManager.user;
	if (!user || !user.userId) {
	  uni.showToast({ title: '请先登录', icon: 'none' });
	  return;
	}
	const addressId = defaultAddress.value.addressId;
	  if (!addressId) {
	    uni.showToast({ title: '请选择收货地址', icon: 'none' });
	    return;
	  }
	if (checkedItems.value.length === 0) {
	    uni.showToast({ title: '没有可支付的商品', icon: 'none' });
	    return;
	  }
	// 提取 cartIds（注意：你的 checkedItems 来自购物车，应包含 cartId）
	  const cartIds = checkedItems.value.map(item => item.cartId);
	  console.log('cartIds:',cartIds);
	  if (cartIds.some(id => !id)) {
	    console.warn('部分商品缺少 cartId:', checkedItems.value);
	    uni.showToast({ title: '商品数据异常', icon: 'none' });
	    return;
	  }
	
	  uni.showLoading({ title: '创建订单中...' });
	  
	  try {
	      const orderNumbers = await createOrder(addressId, cartIds);
	      if (orderNumbers && orderNumbers.length > 0) {
	        uni.hideLoading();
	        //创建成功，跳转到支付页面（可传订单号）
	        uni.reLaunch({
	          url: `/pages/orders/orders`
	        });
			console.log('完成下订单');
	      }
	    } catch (err) {
	      uni.hideLoading();
	      console.error('支付流程异常:', err);
	      uni.showToast({ title: '下单失败，请重试', icon: 'none' });
	    }
	
}

// 加载默认地址的函数
const loadDefaultAddress = async () => {
  try {
    const addr = await getDefaultAddress()
    if (addr) {
      defaultAddress.value = addr
    } else {
      uni.showToast({ title: '请先设置收货地址', icon: 'none' })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/address/list' })
      }, 1000)
    }
  } catch (err) {
    console.error('加载地址失败:', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  }
}
</script>

<style scoped>
.confirm-page {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.address-box {
  background: #ffffff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  position: relative;
}

.default-mark {
  color: #e64340;
  font-size: 24rpx;
  background: #ffecec;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-right: 16rpx;
}

.warn-mark {
  color: #999;
  font-size: 24rpx;
  margin-right: 16rpx;
}

.area-address {
  font-size: 30rpx;
  color: #333;
  display: block;
  margin: 10rpx 0;
}

.detail-address,
.accept-cellphone {
  font-size: 28rpx;
  color: #666;
  margin: 8rpx 0;
  line-height: 1.4;
}

.gt {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 36rpx;
  color: #ccc;
}

.confirm-goods-container {
  position: relative;
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.confirm-goods-list {
  padding: 20rpx;
  max-height: calc(100vh - 220rpx); /* 留出更多底部空间 */
  overflow-y: auto;
  padding-bottom: 180rpx; /* 👈 关键：增大底部留白，防止内容紧贴合计 */
}

.confirm-goods-item {
  display: flex;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.confirm-goods-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border: none;
}

.confirm-goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.confirm-goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  word-break: break-all;
}

.goods-price {
  color: #e64340;
  font-size: 28rpx;
  font-weight: bold;
}

.goods-num {
  color: #999;
  font-size: 26rpx;
  align-self: flex-end;
}

/* 合计金额：下移，增加与商品的间距 */
.total-text {
  position: absolute;
  bottom: 110rpx; /* 👈 从 80rpx → 110rpx */
  left: 30rpx;
  font-size: 32rpx;
  color: #333;
}

.total-amount {
  color: #e64340;
  font-weight: bold;
}

/* 支付按钮：下移，避免紧贴底部 */
.pay-btn {
  position: absolute;
  bottom: 50rpx; /* 👈 从 30rpx → 50rpx */
  right: 30rpx;
  width: 200rpx;
  height: 80rpx;
  background-color: #e64340;
  color: white;
  font-size: 32rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(230, 67, 64, 0.3);
}
</style>